package com.example.joblinker.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.joblinker.dto.JobFairDTO;
import com.example.joblinker.entity.JobFair;
import com.example.joblinker.entity.CompanyJobFair;
import com.example.joblinker.entity.Company;
import com.example.joblinker.entity.Job;
import com.example.joblinker.entity.UserJobFair;
import com.example.joblinker.mapper.JobFairMapper;
import com.example.joblinker.mapper.CompanyJobFairMapper;
import com.example.joblinker.mapper.CompanyMapper;
import com.example.joblinker.mapper.JobMapper;
import com.example.joblinker.mapper.UserJobFairMapper;
import com.example.joblinker.service.JobFairService;
import com.example.joblinker.vo.JobFairVO;
import com.example.joblinker.vo.CompanyVO;
import com.example.joblinker.vo.JobVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.ArrayList;
import java.util.Objects;

@Service
public class JobFairServiceImpl implements JobFairService {

    @Resource
    private JobFairMapper jobFairMapper;

    @Resource
    private CompanyJobFairMapper companyJobFairMapper;

    @Resource
    private CompanyMapper companyMapper;

    @Resource
    private JobMapper jobMapper;

    @Resource
    private UserJobFairMapper userJobFairMapper;

    @Override
    @Transactional
    public JobFairVO createJobFair(JobFairDTO jobFairDTO) {
        // 参数校验
        if (jobFairDTO.getEndTime().isBefore(jobFairDTO.getStartTime())) {
            throw new IllegalArgumentException("结束时间不能早于开始时间");
        }

        // 创建实体并设置默认值
        JobFair jobFair = new JobFair();
        BeanUtils.copyProperties(jobFairDTO, jobFair);
        
        // 处理行业字段 - 将List转为逗号分隔的字符串
        if (jobFairDTO.getIndustryIds() != null && !jobFairDTO.getIndustryIds().isEmpty()) {
            String industriesStr = jobFairDTO.getIndustryIds().stream()
                    .map(String::valueOf)
                    .collect(Collectors.joining(","));
            jobFair.setIndustries(industriesStr);
        }
        
        jobFair.setStatus(0); // 未开始
        jobFair.setRegisteredCompanies(0);
        jobFair.setRegisteredUsers(0);
        jobFair.setCreateTime(LocalDateTime.now());
        jobFair.setUpdateTime(LocalDateTime.now());
        jobFair.setDeleted(0);

        // 保存到数据库
        jobFairMapper.insert(jobFair);

        // 返回VO
        return convertToVO(jobFair);
    }

    @Override
    @Transactional
    public JobFairVO updateJobFair(Long id, JobFairDTO jobFairDTO) {
        // 查询是否存在
        JobFair jobFair = jobFairMapper.selectById(id);
        if (jobFair == null) {
            throw new RuntimeException("招聘会不存在");
        }

        // 只能修改未开始的招聘会
        if (jobFair.getStatus() != 0) {
            throw new RuntimeException("只能修改未开始的招聘会");
        }

        // 参数校验
        if (jobFairDTO.getEndTime().isBefore(jobFairDTO.getStartTime())) {
            throw new IllegalArgumentException("结束时间不能早于开始时间");
        }

        // 更新实体
        BeanUtils.copyProperties(jobFairDTO, jobFair);
        
        // 处理行业字段 - 将List转为逗号分隔的字符串
        if (jobFairDTO.getIndustryIds() != null && !jobFairDTO.getIndustryIds().isEmpty()) {
            String industriesStr = jobFairDTO.getIndustryIds().stream()
                    .map(String::valueOf)
                    .collect(Collectors.joining(","));
            jobFair.setIndustries(industriesStr);
        }
        
        jobFair.setUpdateTime(LocalDateTime.now());

        // 保存到数据库
        jobFairMapper.updateById(jobFair);

        // 返回VO
        return convertToVO(jobFair);
    }

    @Override
    public JobFairVO getJobFairDetail(Long id) {
        JobFair jobFair = jobFairMapper.selectById(id);
        if (jobFair == null) {
            throw new RuntimeException("招聘会不存在");
        }
        return convertToVO(jobFair);
    }

    @Override
    public Page<JobFairVO> getJobFairList(Integer page, Integer size, String title, Integer status) {
        Page<JobFair> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<JobFair> queryWrapper = new LambdaQueryWrapper<>();
        
        // 标题模糊查询
        if (StringUtils.hasText(title)) {
            queryWrapper.like(JobFair::getTitle, title);
        }
        
        // 状态查询
        if (status != null) {
            queryWrapper.eq(JobFair::getStatus, status);
        }
        
        // 按创建时间倒序排序
        queryWrapper.orderByDesc(JobFair::getCreateTime);
        
        // 查询结果
        Page<JobFair> jobFairPage = jobFairMapper.selectPage(pageParam, queryWrapper);
        
        // 转换为VO
        Page<JobFairVO> voPage = new Page<>(jobFairPage.getCurrent(), jobFairPage.getSize(), jobFairPage.getTotal());
        voPage.setRecords(jobFairPage.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList()));
        
        return voPage;
    }

    @Override
    @Transactional
    public void cancelJobFair(Long id) {
        JobFair jobFair = jobFairMapper.selectById(id);
        if (jobFair == null) {
            throw new RuntimeException("招聘会不存在");
        }
        
        // 只能取消未开始的招聘会
        if (jobFair.getStatus() != 0) {
            throw new RuntimeException("只能取消未开始的招聘会");
        }
        
        // 更新状态为已取消
        jobFair.setStatus(3);
        jobFair.setUpdateTime(LocalDateTime.now());
        jobFairMapper.updateById(jobFair);
    }

    @Override
    @Transactional
    public boolean registerForJobFair(Long jobFairId, Long userId) {
        JobFair jobFair = jobFairMapper.selectById(jobFairId);
        if (jobFair == null) {
            throw new RuntimeException("招聘会不存在");
        }
        
        // 检查招聘会状态
        if (jobFair.getStatus() != 0) {
            throw new RuntimeException("只能报名未开始的招聘会");
        }
        
        // 检查容量
        if (jobFair.getRegisteredUsers() >= jobFair.getUserLimit()) {
            throw new RuntimeException("招聘会求职者名额已满");
        }
        
        // 检查用户是否已报名
        LambdaQueryWrapper<UserJobFair> checkWrapper = new LambdaQueryWrapper<>();
        checkWrapper.eq(UserJobFair::getJobFairId, jobFairId)
                   .eq(UserJobFair::getUserId, userId);
        Long count = userJobFairMapper.selectCount(checkWrapper);
        
        if (count > 0) {
            throw new RuntimeException("您已报名此招聘会，请勿重复报名");
        }
        
        // 增加报名人数
        jobFair.setRegisteredUsers(jobFair.getRegisteredUsers() + 1);
        jobFair.setUpdateTime(LocalDateTime.now());
        jobFairMapper.updateById(jobFair);
        
        // 保存用户报名记录
        UserJobFair userJobFair = new UserJobFair();
        userJobFair.setUserId(userId);
        userJobFair.setJobFairId(jobFairId);
        userJobFair.setStatus(0); // 已报名
        userJobFair.setRegisterTime(LocalDateTime.now());
        userJobFair.setCreateTime(LocalDateTime.now());
        userJobFair.setUpdateTime(LocalDateTime.now());
        userJobFairMapper.insert(userJobFair);
        
        return true;
    }

    @Override
    @Transactional
    public boolean registerCompanyForJobFair(Long jobFairId, Long companyId) {
        JobFair jobFair = jobFairMapper.selectById(jobFairId);
        if (jobFair == null) {
            throw new RuntimeException("招聘会不存在");
        }
        
        // 检查招聘会状态
        if (jobFair.getStatus() != 0) {
            throw new RuntimeException("只能报名未开始的招聘会");
        }
        
        // 检查容量
        if (jobFair.getRegisteredCompanies() >= jobFair.getCompanyLimit()) {
            throw new RuntimeException("招聘会企业名额已满");
        }
        
        // 检查企业是否已报名
        LambdaQueryWrapper<CompanyJobFair> checkWrapper = new LambdaQueryWrapper<>();
        checkWrapper.eq(CompanyJobFair::getJobFairId, jobFairId)
                    .eq(CompanyJobFair::getCompanyId, companyId);
        Long count = companyJobFairMapper.selectCount(checkWrapper);
        
        if (count > 0) {
            throw new RuntimeException("该企业已报名此招聘会");
        }
        
        // 保存企业报名记录
        CompanyJobFair relation = new CompanyJobFair();
        relation.setCompanyId(companyId);
        relation.setJobFairId(jobFairId);
        relation.setStatus(1); // 默认已确认
        relation.setRegisterTime(LocalDateTime.now()); // 设置注册时间
        relation.setCreateTime(LocalDateTime.now());
        relation.setUpdateTime(LocalDateTime.now());
        
        companyJobFairMapper.insert(relation);
        
        // 增加报名企业数
        jobFair.setRegisteredCompanies(jobFair.getRegisteredCompanies() + 1);
        jobFair.setUpdateTime(LocalDateTime.now());
        jobFairMapper.updateById(jobFair);
        
        return true;
    }
    
    /**
     * 更新招聘会状态（定时任务调用）
     */
    public void updateJobFairStatus() {
        LocalDateTime now = LocalDateTime.now();
        
        // 更新已开始的招聘会
        LambdaQueryWrapper<JobFair> startWrapper = new LambdaQueryWrapper<>();
        startWrapper.eq(JobFair::getStatus, 0)
                .le(JobFair::getStartTime, now);
        JobFair startUpdate = new JobFair();
        startUpdate.setStatus(1);
        startUpdate.setUpdateTime(now);
        jobFairMapper.update(startUpdate, startWrapper);
        
        // 更新已结束的招聘会
        LambdaQueryWrapper<JobFair> endWrapper = new LambdaQueryWrapper<>();
        endWrapper.eq(JobFair::getStatus, 1)
                .le(JobFair::getEndTime, now);
        JobFair endUpdate = new JobFair();
        endUpdate.setStatus(2);
        endUpdate.setUpdateTime(now);
        jobFairMapper.update(endUpdate, endWrapper);
    }
    
    /**
     * 转换为VO对象
     */
    private JobFairVO convertToVO(JobFair jobFair) {
        if (jobFair == null) {
            return null;
        }
        
        JobFairVO vo = new JobFairVO();
        BeanUtils.copyProperties(jobFair, vo);
        
        // 填充状态名称
        String statusName;
        switch (jobFair.getStatus()) {
            case 0:
                statusName = "未开始";
                break;
            case 1:
                statusName = "进行中";
                break;
            case 2:
                statusName = "已结束";
                break;
            case 3:
                statusName = "已取消";
                break;
            default:
                statusName = "未知状态";
        }
        vo.setStatusName(statusName);
        
        // 填充类型名称
        String typeName = jobFair.getType() == null ? "未知" : (jobFair.getType() == 0 ? "线下招聘会" : "线上招聘会");
        vo.setTypeName(typeName);
        
        // 处理行业
        if (jobFair.getIndustries() != null && !jobFair.getIndustries().isEmpty()) {
            // 将逗号分隔的行业ID转换为列表
            List<Integer> industryIds = Arrays.stream(jobFair.getIndustries().split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            vo.setIndustryIds(industryIds);
            
            // TODO: 根据行业ID查询行业名称
            // 这里暂时使用模拟数据
            Map<Integer, String> industryMap = new HashMap<>();
            industryMap.put(1, "互联网/IT");
            industryMap.put(2, "金融");
            industryMap.put(3, "教育");
            industryMap.put(4, "医疗");
            industryMap.put(5, "制造业");
            
            List<String> industries = industryIds.stream()
                    .map(id -> industryMap.getOrDefault(id, "未知行业"))
                    .collect(Collectors.toList());
            vo.setIndustries(industries);
        }
        
        // 招聘职位数暂定为0，实际应该关联查询
        vo.setPositions(0);
        
        return vo;
    }

    @Override
    public List<CompanyVO> getJobFairCompanies(Long jobFairId) {
        // 检查招聘会是否存在
        JobFair jobFair = jobFairMapper.selectById(jobFairId);
        if (jobFair == null) {
            throw new RuntimeException("招聘会不存在");
        }
        
        // 查询报名该招聘会的企业关联记录
        LambdaQueryWrapper<CompanyJobFair> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CompanyJobFair::getJobFairId, jobFairId)
               .eq(CompanyJobFair::getStatus, 1); // 仅查询已确认的企业

        
        List<CompanyJobFair> relations = companyJobFairMapper.selectList(wrapper);
        
        // 如果没有企业报名，返回空列表
        if (relations.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 获取企业ID列表
        List<Long> companyIds = relations.stream()
                .map(CompanyJobFair::getCompanyId)
                .collect(Collectors.toList());
        
        // 查询企业信息
        LambdaQueryWrapper<Company> companyWrapper = new LambdaQueryWrapper<>();
        companyWrapper.in(Company::getId, companyIds)
                      .eq(Company::getStatus, 1); // 仅查询状态正常的企业
        
        List<Company> companies = companyMapper.selectList(companyWrapper);
        
        // 转换为VO对象并设置展位号
        return companies.stream().map(company -> {
            CompanyVO vo = new CompanyVO();
            BeanUtils.copyProperties(company, vo);
            
            // 设置展位号
            relations.stream()
                    .filter(r -> r.getCompanyId().longValue() == company.getId().longValue())
                    .findFirst()
                    .ifPresent(r -> vo.setBoothNumber(r.getBoothNumber()));
            
            return vo;
        }).collect(Collectors.toList());
    }
    
    @Override
    public boolean isCompanyRegistered(Long jobFairId, Long companyId) {
        // 检查招聘会是否存在
        JobFair jobFair = jobFairMapper.selectById(jobFairId);
        if (jobFair == null) {
            throw new RuntimeException("招聘会不存在");
        }

        // 查询企业是否已报名
        LambdaQueryWrapper<CompanyJobFair> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CompanyJobFair::getJobFairId, jobFairId)
                .eq(CompanyJobFair::getCompanyId, companyId);
        Long count = companyJobFairMapper.selectCount(wrapper);
        return count > 0;
    }
    
    @Override
    public List<JobVO> getJobFairJobs(Long jobFairId) {
        // 检查招聘会是否存在
        JobFair jobFair = jobFairMapper.selectById(jobFairId);
        if (jobFair == null) {
            throw new RuntimeException("招聘会不存在");
        }
        
        // 获取已报名的企业ID列表
        LambdaQueryWrapper<CompanyJobFair> companyWrapper = new LambdaQueryWrapper<>();
        companyWrapper.eq(CompanyJobFair::getJobFairId, jobFairId);
        List<CompanyJobFair> companyJobFairs = companyJobFairMapper.selectList(companyWrapper);
        
        if (companyJobFairs.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 获取这些企业发布的职位
        List<Long> companyIds = companyJobFairs.stream()
                .map(CompanyJobFair::getCompanyId)
                .collect(Collectors.toList());
        
        // 查询这些企业的有效职位
        LambdaQueryWrapper<Job> jobWrapper = new LambdaQueryWrapper<>();
        jobWrapper.in(Job::getCompanyId, companyIds)
                .eq(Job::getStatus, 1); // 状态1表示已发布的职位
        
        List<Job> jobs = jobMapper.selectList(jobWrapper);
        
        // 转换为JobVO
        return jobs.stream().map(job -> {
            JobVO jobVO = new JobVO();
            BeanUtils.copyProperties(job, jobVO);
            
            // 获取公司信息
            Company company = companyMapper.selectById(job.getCompanyId());
            if (company != null) {
                jobVO.setCompanyName(company.getName());
                jobVO.setCompanyLogo(company.getLogo());
            }
            
            return jobVO;
        }).collect(Collectors.toList());
    }
    
    @Override
    public boolean isUserRegistered(Long jobFairId, Long userId) {
        // 检查招聘会是否存在
        JobFair jobFair = jobFairMapper.selectById(jobFairId);
        if (jobFair == null) {
            throw new RuntimeException("招聘会不存在");
        }
        
        // 查询用户是否已报名
        LambdaQueryWrapper<UserJobFair> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserJobFair::getJobFairId, jobFairId)
               .eq(UserJobFair::getUserId, userId);
        
        return userJobFairMapper.selectCount(wrapper) > 0;
    }
} 